package com.guangyuan.network.mvc.handler;

import java.io.IOException;
import java.io.InputStream;

import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.collections.ExtendedProperties;
import org.apache.log4j.Logger;
import org.apache.velocity.Template;
import org.apache.velocity.app.VelocityEngine;
import org.apache.velocity.exception.ParseErrorException;
import org.apache.velocity.exception.ResourceNotFoundException;

import com.guangyuan.network.context.WebVelocityContext;
import com.guangyuan.network.mvc.view.ContextAndTemplate;
import com.guangyuan.network.util.Messages;

public abstract class AbstractHandler implements Handler {
	protected static Logger logger = Logger
			.getLogger(AddProductGroupHandler.class);

	protected static VelocityEngine velocity = null;
	/**
	 * Default Runtime properties. 加载配置文件，里面定义了加载资源的类
	 */
	private static final String DEFAULT_TOOLS_PROPERTIES = "/org/apache/velocity/tools/view/servlet/velocity.properties";
	/**
	 * Key used to access the ServletContext in the Velocity application
	 * attributes. 与加载页面资源的类中定义的名称一致
	 */
	private static final String SERVLET_CONTEXT_KEY = ServletContext.class
			.getName();

	public static void initVelocity(ServletConfig config,
			ServletContext servletContext) {
		velocity = new VelocityEngine();
		velocity.setApplicationAttribute(SERVLET_CONTEXT_KEY, servletContext);

		ExtendedProperties defaultProperties = loadDefaultProperties();
		velocity.setExtendedProperties(defaultProperties);
	}

	private static ExtendedProperties loadDefaultProperties() {
		InputStream inputStream = null;
		ExtendedProperties defaultProperties = new ExtendedProperties();

		try {
			inputStream = AbstractHandler.class
					.getResourceAsStream(DEFAULT_TOOLS_PROPERTIES);
			if (inputStream != null) {
				defaultProperties.load(inputStream);
			}
		} catch (IOException ioe) {
			logger.error("Cannot load default extendedProperties!", ioe);
		} finally {
			try {
				if (inputStream != null) {
					inputStream.close();
				}
			} catch (IOException ioe) {
				logger.error("Cannot close default extendedProperties!", ioe);
			}
		}
		return defaultProperties;
	}

	public static Template getTemplate(String name) {
		Template template = null;
		try {
			template = velocity.getTemplate(name, "utf-8");
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return template;
	}

	protected ContextAndTemplate getContextAndTemplate(String name,
			HttpServletRequest request, HttpServletResponse response,
			ServletContext servletContext) {
		Template template = null;
		WebVelocityContext context = null;
		try {
			template = velocity.getTemplate(name, Messages
					.getString("Encoding"));
			
			context = new WebVelocityContext(servletContext, request, response,
					request.getSession(false));
		} catch (ResourceNotFoundException e) {
			logger.error(e.getMessage());
		} catch (ParseErrorException e) {
			logger.error(e.getMessage());
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		if(null == template) {
			return null;
		}
		return new ContextAndTemplate(template, context); 
	}
}
